package com.codingbee.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import static com.codingbee.util.Const.*;


/**
 * @Description RabbitMQ 相关配置类
 * @Author zouxiang
 * @Date 2020/4/3/19:44
 */
@Configuration
public class MyAMQPConfig {

    /**
     * 配置消息转换器
     * @return
     */
    @Bean
    public MessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    /**
     * 延时交换器，用于处理死信的交换器
     * @return
     */
    @Bean("delayDirectExchange")
    public DirectExchange delayDirectExchange() {
        return new DirectExchange(DELAY_EXCHANGE_NAME);
    }

    /**
     * 延迟队列，该队列没有消费者
     * @return
     */
    @Bean("delayQueuePerMessageTTL")
    public Queue delayQueuePerMessageTTL() {
        return QueueBuilder.durable(DELAY_QUEUE_PER_QUEUE_TTL_NAME)
                .withArgument("x-dead-letter-exchange", DELAY_EXCHANGE_NAME) // DLX，dead letter发送到的exchange
                .withArgument("x-dead-letter-routing-key", DELAY_PROCESS_QUEUE_NAME_ROUTING_KEY) // dead letter携带的routing key
                .build();
    }

    /**
     * 延迟处理队列，用于处理已经过了延迟的消息
     * @return
     */
    @Bean("delayProcessQueue")
    Queue delayProcessQueue() {
        return QueueBuilder.durable(DELAY_PROCESS_QUEUE_NAME)
                .build();
    }

    /**
     * 将延时处理队列与延时交换器绑定。这样所有的死信都会通过延时交换器发送到延时处理队列中
     * @param delayProcessQueue
     * @param delayDirectExchange
     * @return
     */
    @Bean
    Binding dlxBinding(Queue delayProcessQueue, DirectExchange delayDirectExchange) {
        return BindingBuilder.bind(delayProcessQueue)   //处理延时订单的队列
                .to(delayDirectExchange)        //分发延时订单信息的交换器
                .with(DELAY_PROCESS_QUEUE_NAME_ROUTING_KEY);    //分配信息的路由键
    }

}
